package com.listerner;

import com.alibaba.fastjson.JSONObject;
import com.bean.ResponseBean;
import com.pojo.Room;
import com.service.RoomService;
import com.util.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

@Component
public class ApiInterceptor implements HandlerInterceptor {

    private RedisTemplate redisTemplate;

    @Autowired
    private RoomService roomService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RedissonClient redissonClient;

    @Value("${server.url}")
    private String server;


    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public synchronized boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {

            if (server.startsWith("http://172.") || server.startsWith("http://192.") || server.startsWith("http://10.")){
                return true;
            }

            InputStream is = null;
            try {
                is = new FileInputStream("ip.properties");
                Properties p = new Properties();
                p.load(is);
                String ip2 = p.getProperty("server.ip");
                if (StringUtils.isEmpty(ip2) == true) {

                }
                else{
                    if (ip2.startsWith("10.") || ip2.startsWith("192.") || ip2.startsWith("172."))
                    {

                    }else{
                        return true;
                    }
                }

            } catch (Exception e) {

            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    // e.printStackTrace();
                }
            }


            if (redisTemplate==null)
            {
                redisTemplate = (RedisTemplate)applicationContext.getBean("StringRedisTemplate");
            }
            Object obj = redisTemplate.boundValueOps("local_expire").get();
            ;
            Long t = Long.parseLong(obj.toString());
            Integer m = (Integer) redisTemplate.boundValueOps("local_max").get();
            if (t == null || m == null) {
                response.setContentType("text/html;charset=utf-8");
                ResponseBean responseBean = new ResponseBean(500, "授权失败", null);
                String str = JSONObject.toJSONString(responseBean);
                response.getWriter().println(str);
                return false;
            }
            if (t < System.currentTimeMillis()) { //已过期
                response.setContentType("text/html;charset=utf-8");
                ResponseBean responseBean = new ResponseBean(500, "授权已过期", null);
                String str = JSONObject.toJSONString(responseBean);
                response.getWriter().println(str);
                return false;
            }

            //BoundSetOperations set = redisTemplate.boundSetOps("local_termal");
            //long size = set.size();
            long size = roomService.count();
            if (size > m) {
                response.setContentType("text/html;charset=utf-8");
                ResponseBean responseBean = new ResponseBean(500, "超过最大终端数", null);
                String str = JSONObject.toJSONString(responseBean);
                response.getWriter().println(str);
                return false;
            }
            String mac = request.getHeader("mac");
            if (mac == null) {
                response.setContentType("text/html;charset=utf-8");
                ResponseBean responseBean = new ResponseBean(500, "缺少参数", null);
                String str = JSONObject.toJSONString(responseBean);
                response.getWriter().println(str);
                return false;
            }
            //RLock rLock = redissonClient.getLock("apiLock");
            //boolean lockResult = rLock.tryLock(200,300, TimeUnit.MILLISECONDS);
            try {
                if (true) {
                    Room room = roomService.getRoomByMac(mac);
                    boolean f = room != null;
                    String ver = request.getHeader("ver");
                    String roomNum = request.getHeader("room");
                    String type = request.getHeader("type");
                    if (room == null) {      //如果不存在集合中
                        if (size == m) {
                            response.setContentType("text/html;charset=utf-8");
                            ResponseBean responseBean = new ResponseBean(500, "超过最大终端数", null);
                            String str = JSONObject.toJSONString(responseBean);
                            response.getWriter().println(str);
                            return false;
                        }

                        //set.add(mac);
                        Room pojo = new Room();
                        pojo.setOnline(1);
                        pojo.setMac(mac);
                        pojo.setRoom(roomNum);
                        pojo.setCreateTime(new Date(System.currentTimeMillis()));
                        pojo.setType(type);
                        pojo.setVer(ver);
                        roomService.save(pojo);
                        //发送新增指令
                        roomService.sendSave(pojo);
                    } else {

                        if (room.getOnline() == 0) {
                            //发送在线的指令
                            roomService.sendOnline(mac, 1);
                        }
                        room.setOnline(1);
                        room.setMac(mac);
                        room.setCreateTime(new Date(System.currentTimeMillis()));
                        room.setType(type);
                        room.setVer(ver);
                        if (StringUtils.isEmpty(roomNum)==false)
                        {
                            room.setRoom(roomNum);
                        }
                        roomService.updateById(room);


                    }
                }
            }finally {
                //rLock.unlock();
            }


            return true;


        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("text/html;charset=utf-8");
            ResponseBean responseBean = new ResponseBean(500, "缺少参数", null);
            String str = JSONObject.toJSONString(responseBean);
            try {
                response.getWriter().println(str);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
        return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}